package org.fuys.coder.infrastructure.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.fuys.coder.common.exception.db.DuplicateDataException;
import org.fuys.coder.common.util.EncryptUtil;
import org.fuys.coder.domain.auth.model.req.LoginReq;
import org.fuys.coder.domain.auth.model.vo.UserVo;
import org.fuys.coder.domain.auth.repository.ICommonRepository;
import org.fuys.coder.infrastructure.dao.UserMapper;
import org.fuys.coder.infrastructure.model.po.User;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * @projectName: fuys-low-coder
 * @package: org.fuys.coder.infrastructure.repository
 * @className: CommonAuthRepository
 * @author: WangJing
 * @description: 持久层仓储
 * @date: 2024/6/18 20:28
 * @version: 1.0
 */
@Service
public class CommonRepository extends ServiceImpl<UserMapper, User>
        implements ICommonRepository {

    @Resource
    private UserMapper userMapper;

    @Resource
    private EncryptUtil encryptUtil;

    @Override
    public int insertUser(String email,String password,String username
            ,String avatar,Integer point) {
        try {
            User user = new User();
            //加密密码
            user.setPassword(encryptUtil.encodePassword(password));
            user.setEmail(email);
            user.setNickName(username);
            user.setPoints(point);
            user.setAvatar(avatar);
            userMapper.insert(user);
            return user.getId();
        }catch (DuplicateKeyException e){
            throw new DuplicateDataException("邮箱已经被注册了");
        }
    }

    @Override
    public UserVo selectUser(LoginReq req) {
        final User one = this.getOne(new LambdaQueryWrapper<User>().select(User::getId,User::getAvatar,User::getNickName,User::getPassword,User::getPoints)
                .eq(User::getEmail,req.getEmail()));
        if(ObjectUtils.isEmpty(one)){
            return null;
        }
        UserVo userVo=new UserVo();
        userVo.setUsername(one.getNickName());
        userVo.setEmail(one.getEmail());
        userVo.setId(one.getId());
        userVo.setPassword(one.getPassword());
        userVo.setAvatar(one.getAvatar());
        return userVo;
    }
}
